<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category OnlineService.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/5/20  15:18
 * +--------------------------------------------------------+
 */

namespace App\Services\Swoole\Components;


use App\Models\StockArticle;
use App\Util\FileSystem;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Swoole\Coroutine;
use Swoole\Coroutine\WaitGroup;
use function Swoole\Coroutine\run;

/**
 * Class SendService 记录聊天
 * @package App\Services\Swoole\Components
 */
class SendService implements ComponentsInterface
{
    public $ws;
    public $frame;

    public function handle()
    {
        $user = Cache::get('user_info_' . $this->frame->fd);
        $data = json_decode($this->frame->data, true);;
        $message   = $data['data']['message'];
        $groupChat = Cache::get('groupChat', collect());
        $admin     = $user->id;

        if ($admin !== null) {

            $content = collect([
                [
                    'clientId'   => $user->id,
                    'name'       => $user->name,
                    'message'    => $message,
                    'created_at' => Carbon::now(config('app.timezone'))->toISOString(),
                ],
            ]);
            $merged  = $groupChat->merge($content);
            Cache::store('redis')->put('groupChat', $merged, 600);
        }

        $res_data['message'] = $message;

        return $res = response_success_msg('请求成功！', $res_data);
    }

    private function ybsImage()
    {

        $show_url = StockArticle::query()
            ->select('subjectId', 'type')
            ->orderBy('id', 'desc')
            ->chunk(30, function ($datas) {

                $wg = new WaitGroup();
                foreach ($datas as $data) {
                    $wg->add();
                    Coroutine::create(function ($data) use ($wg, &$result) {
                        //启动一个协程

                        $show_url = 'https://yanbaoshe.oss-cn-beijing.aliyuncs.com/images/prod-gb-share_zlArticle_' . $data['subjectId'] . '.png';
                        // 拉取图片到本地
                        $fileSystem = $fileSystem = new FileSystem('');
                        $result[]   = $res = $fileSystem->getImage($show_url, 'prod-gb-share_zlArticle_' . $data['subjectId'] . '.png', 'downloads/');
                        Log::info('【' . $data['id'] . '】' . $res);
                        $wg->done();
                    }, $data);
                }

                //挂起当前协程，等待所有任务完成后恢复
                $wg->wait();
                //这里 $result 包含了 2 个任务执行结果


                return $result;

            });


        return true;
    }

}
